package redis_ser

import (
	"blog_go/global"
	"github.com/sirupsen/logrus"
	"strconv"
)

type DiggPre string

const (
	articleDigg DiggPre = "article_digg_key"
	articleLook DiggPre = "article_look_key"
	commentDigg DiggPre = "comment_digg_key"
)

type RedisDigg struct {
	pre DiggPre // 前缀
}

func (digg RedisDigg) DiggIncr(id uint) {
	redisKey := string(digg.pre)
	global.Redis.HIncrBy(redisKey, strconv.FormatUint(uint64(id), 10), 1)
}

func (digg RedisDigg) DiggGet(id uint) int {
	redisKey := string(digg.pre)
	count, _ := global.Redis.HGet(redisKey, strconv.FormatUint(uint64(id), 10)).Int()
	return count
}

func (digg RedisDigg) DiggGetAll() map[uint]int {
	redisKey := string(digg.pre)
	result, err := global.Redis.HGetAll(redisKey).Result()
	if err != nil {
		logrus.Error(err)
		panic(err)
	}
	idCountMap := map[uint]int{}
	for idStr, countStr := range result {
		var (
			err   error
			id    int
			count int
		)
		id, err = strconv.Atoi(idStr)
		count, err = strconv.Atoi(countStr)
		if err != nil {
			logrus.Error(err)
			continue
		}
		idCountMap[uint(id)] = count
	}
	return idCountMap
}

func (digg RedisDigg) DiggSetAll(countMap map[uint]int) {
	redisKey := string(digg.pre)
	countMapStr := map[string]interface{}{}
	for u, i := range countMap {
		countMapStr[strconv.Itoa(int(u))] = i
	}
	global.Redis.HMSet(redisKey, countMapStr)
}

func (digg RedisDigg) DiggClear(id uint) {
	redisKey := string(digg.pre)
	global.Redis.HDel(redisKey, strconv.FormatUint(uint64(id), 10))
}

func NewArticleDigg() RedisDigg {
	return RedisDigg{articleDigg}
}
func NewArticleLook() RedisDigg {
	return RedisDigg{articleLook}
}
func NewCommentDigg() RedisDigg {
	return RedisDigg{commentDigg}
}
